<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>折线</title>
  <style>
    body {
      background: black;
    }

    .svg-wrap {
      width: 400px;
      height: 400px;
      background: white;
      margin: 0 auto;
    }

  </style>
</head>

<body>
  <div class="svg-wrap" id="svg_wrap">
    <!-- <svg>
      <polyline points="10 50,100 70,100 300,200 400,10 10" fill="none" stroke="red" stroke-width="2"></polyline>
    </svg> -->
  </div>

  <script>
    function createSvgNode(tagName, props) {
      const node = document.createElementNS('http://www.w3.org/2000/svg', tagName);
      if (props) {
        for (const prop in props) {
          node.setAttribute(prop, props[prop]);
        }
      }
      return node;
    }

    const divBox = document.querySelector('#svg_wrap');
    const svg = createSvgNode('svg', {
      width: '100%',
      height: '100%'
    });
    divBox.appendChild(svg);

    let polyLine = null;
    let pointNums = '';
    svg.onmousedown = function (ev) {
      if (!polyLine) {
        polyLine = createSvgNode('polyline', {
          fill: 'none',
          stroke: 'red',
          'strokr-width': 2
        });
        svg.appendChild(polyLine);
      }
      const x = ev.clientX - divBox.offsetLeft;
      const y = ev.clientY - divBox.offsetTop;
      if (pointNums == '') {
        pointNums = x + ',' + y;
      } else {
        pointNums += ',' + x + ',' + y;
      }
      const circle = createSvgNode('circle', {
        cx: x,
        cy: y,
        r: 5,
        fill: 'none',
        stroke: 'red',
        'stroke-width': 1
      });
      svg.appendChild(circle);
      polyLine.setAttribute('points', pointNums);
    }
    svg.onmousemove = function (ev) {
      if (polyLine) {
        const x = ev.clientX - divBox.offsetLeft;
        const y = ev.clientY - divBox.offsetTop;
        polyLine.setAttribute('points', pointNums + ',' + x + ',' + y);
      }
    }

    //鼠标右键 停止画线
    svg.oncontextmenu = function () {
      svg.onmousemove = null;
      return false;
    }

    // const circle = createSvgNode('circle', {
    //   cx: 200,
    //   cy: 200,
    //   r: 100,
    //   fill: 'transparent',
    //   'stroke-width': 2,
    //   stroke: 'red'
    // })
    // svg.appendChild(circle);

  </script>
</body>

</html>
